<template>
  <div class="list-common-table">
    <t-form ref="form" :data="user" :label-width="80" :colon="true" @reset="onReset" @submit="onSubmit">
      <t-row>
        <t-col :span="10">
          <t-row :gutter="[24, 24]">
            <t-col :span="3">
              <t-form-item label="用户名" name="name">
                <t-input
                  v-model="user.name"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入用户名"
                  :style="{ minWidth: '134px' }"
                  :clearable="true"
                />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="账号" name="number">
                <t-input
                  v-model="user.number"
                  class="form-item-content"
                  type="search"
                  placeholder="请输入账号"
                  :style="{ minWidth: '134px' }"
                  :clearable="true"
                />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="用户等级" name="isVIP">
                <t-select
                  v-model="user.isVIP"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="roleOptions"
                  placeholder="请选择用户等级"
                  :clearable="true"
                />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="用户身份" name="isAdmin">
                <t-select
                  v-model="user.isAdmin"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="adminOptions"
                  placeholder="请选择用户身份"
                  :clearable="true"
                />
              </t-form-item>
            </t-col>
            <t-col :span="3">
              <t-form-item label="用户状态" name="status">
                <t-select
                  v-model="user.status"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="statusOptions"
                  placeholder="请选择用户身份"
                  :clearable="true"
                />
              </t-form-item>
            </t-col>
          </t-row>
        </t-col>

        <t-col :span="2" class="operation-container">
          <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }"> 查询 </t-button>
          <t-button type="reset" variant="base" theme="default"> 重置 </t-button>
        </t-col>
      </t-row>
    </t-form>

    <div class="table-container">
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :vertical-align="verticalAlign"
        :hover="hover"
        :pagination="pagination"
        :loading="dataLoading"
        :header-affixed-top="headerAffixedTop"
      >
        <template #is_vip="{ row }">
          <p v-if="row.is_vip === false">普通用户</p>
          <p v-if="row.is_vip === true">VIP用户</p>
        </template>
        <template #is_admin="{ row }">
          <p v-if="row.is_admin === false">使用者</p>
          <p v-if="row.is_admin === true">管理员</p>
        </template>
        <template #status="{ row }">
          <t-tag v-if="row.status === 0" theme="danger" variant="light"> 被禁用 </t-tag>
          <t-tag v-if="row.status === 1" theme="success" variant="light"> 正常 </t-tag>
        </template>
        <template #op="{ row }">
          <t-space>
            <t-link theme="primary" @click="handleClickChange(row)"> 修改 </t-link>
          </t-space>
        </template>
      </t-table>
      <t-dialog v-model:visible="confirmVisibleC" header="用户信息修改" :footer="false">
        <t-space direction="vertical" style="width: 95%">
          <div>
            <t-form ref="form" :data="formData" :colon="true" @reset="onResetC" @submit="onSubmitC">
              <t-form-item label="姓名" name="name">
                <t-input v-model="formData.name" placeholder="请输入用户名"></t-input>
              </t-form-item>
              <t-form-item label="账号" name="number">
                <t-input v-model="formData.number" placeholder="请输入账号"></t-input>
              </t-form-item>
              <t-form-item label="密码" name="password">
                <t-input v-model="formData.password" placeholder="请输入密码"></t-input>
              </t-form-item>
              <t-form-item label="用户等级" name="isVIP">
                <t-select
                  v-model="formData.isVIP"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="roleOptions"
                  placeholder="请选择用户等级"
                  :clearable="true"
                />
              </t-form-item>
              <t-form-item label="用户身份" name="isAdmin">
                <t-select
                  v-model="formData.isAdmin"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="adminOptions"
                  placeholder="请选择用户身份"
                  :clearable="true"
                />
              </t-form-item>
              <t-form-item label="用户状态" name="status">
                <t-select
                  v-model="formData.status"
                  style="display: inline-block"
                  class="form-item-content"
                  :options="statusOptions"
                  placeholder="请选择用户状态"
                  :clearable="true"
                />
              </t-form-item>
              <t-form-item>
                <t-space size="large">
                  <t-button theme="primary" type="submit" style="margin-left: 40px">提交</t-button>
                  <t-button theme="default" variant="base" type="reset">重置</t-button>
                </t-space>
              </t-form-item>
            </t-form>
          </div>
        </t-space>
        <template #footer> </template>
      </t-dialog>
      <t-dialog
        v-model:visible="confirmVisibleD"
        header="确认修改当前所选用户信息？"
        :body="confirmBodyD"
        @confirm="onConfirmChange"
      />
    </div>
  </div>
</template>
<script setup lang="ts">
import axios from 'axios';
import { MessagePlugin, PrimaryTableCol } from 'tdesign-vue-next';
import { computed, onMounted, reactive, ref } from 'vue';

import { prefix } from '@/config/global';
import { useSettingStore } from '@/store';

const user = reactive({
  name: '',
  number: '',
  isVIP: undefined,
  isAdmin: undefined,
  status: undefined,
  queryFlags: {
    queryIsAdmin: false,
    queryIsVIP: false,
    queryStatus: false,
  },
});

const roleOptions = [
  { label: '普通用户', value: false, title: '普通用户' },
  { label: 'VIP用户', value: true, title: '' },
];

const adminOptions = [
  { label: '使用者', value: false, title: '是' },
  { label: '管理员', value: true, title: '' },
];

const statusOptions = [
  { label: '被禁用', value: 0, title: '是' },
  { label: '正常', value: 1, title: '' },
];

const onSubmit = () => {
  user.queryFlags.queryIsAdmin = false;
  user.queryFlags.queryIsVIP = false;
  user.queryFlags.queryStatus = false;
  if (user.isAdmin === false || user.isAdmin === true) {
    user.queryFlags.queryIsAdmin = true;
  }
  if (user.isVIP === false || user.isVIP === true) {
    user.queryFlags.queryIsVIP = true;
  }
  if (user.status === 0 || user.status === 1) {
    user.queryFlags.queryStatus = true;
  }
  console.log(user);
  fetchData();
};

const onReset = () => {
  user.name = '';
  user.number = '';
  user.isVIP = undefined;
  user.isAdmin = undefined;
  user.status = undefined;
  user.queryFlags.queryIsAdmin = false;
  user.queryFlags.queryIsVIP = false;
  user.queryFlags.queryStatus = false;
};

const changed = ref(false);
const changes = ref([]);
const onSubmitC = () => {
  changed.value = false;
  changes.value = [];

  if (formData.name !== formDataCopy.name) {
    changes.value.push(`用户名`);
  }
  if (formData.number !== formDataCopy.number) {
    changes.value.push(`账号`);
  }
  if (formData.password !== formDataCopy.password) {
    changes.value.push(`用户密码`);
  }
  if (formData.isVIP !== formDataCopy.isVIP) {
    changes.value.push(`用户等级`);
  }
  if (formData.isAdmin !== formDataCopy.isAdmin) {
    changes.value.push(`用户身份`);
  }
  if (formData.status !== formDataCopy.status) {
    changes.value.push(`用户状态`);
  }

  if (changes.value.length > 0) {
    changed.value = true;
  }
  if (changed.value) {
    confirmVisibleD.value = true;
  } else {
    MessagePlugin.warning('您没有修改任何信息');
  }
};

const onResetC = () => {
  formData.name = formDataCopy.name;
  formData.number = formDataCopy.number;
  formData.password = formDataCopy.password;
  formData.isVIP = formDataCopy.isVIP;
  formData.isAdmin = formDataCopy.isAdmin;
  formData.status = formDataCopy.status;
};

const pagination = ref({
  defaultPageSize: 20,
  total: 100,
  defaultCurrent: 1,
});

const COLUMNS: PrimaryTableCol[] = [
  { colKey: 'serial-number', width: 80, title: '序号' },
  {
    title: '用户名',
    fixed: 'left',
    width: 180,
    ellipsis: true,
    align: 'left',
    colKey: 'name',
  },
  {
    title: '账号',
    width: 200,
    ellipsis: true,
    colKey: 'number',
  },
  {
    title: '密码',
    width: 200,
    ellipsis: true,
    colKey: 'password',
  },
  {
    title: '用户等级',
    width: 160,
    ellipsis: true,
    colKey: 'is_vip',
  },
  {
    title: '用户身份',
    width: 160,
    ellipsis: true,
    colKey: 'is_admin',
  },
  { title: '用户状态', colKey: 'status', width: 160 },
  {
    align: 'left',
    fixed: 'right',
    width: 160,
    colKey: 'op',
    title: '操作',
  },
];

const verticalAlign = 'top' as const;
const hover = true;
const rowKey = 'index';
const data = ref<userType[]>([]);

interface userType {
  name: string;
  number: string;
  is_vip: boolean;
  is_admin: boolean;
  status: number;
  password: string;
}
const dataLoading = ref(false);
const fetchData = async () => {
  dataLoading.value = true;
  try {
    const response = await axios.post('/api/admin/getUsers', user);
    data.value = response.data.data;
    const list = data.value;
    pagination.value = {
      ...pagination.value,
      total: list.length,
    };
  } catch (e) {
    console.log(e);
  } finally {
    dataLoading.value = false;
  }
};
const store = useSettingStore();
const formData = reactive({
  name: '',
  number: '',
  password: '',
  isVIP: undefined,
  isAdmin: undefined,
  status: undefined,
});
const formDataCopy = reactive({
  name: '',
  number: '',
  password: '',
  isVIP: undefined,
  isAdmin: undefined,
  status: undefined,
});

const confirmVisibleC = ref(false);
const confirmVisibleD = ref(false);
const confirmBodyD = computed(() => {
  return `${changes.value.join(`、`)}将被修改`;
});

const handleClickChange = (row: userType) => {
  confirmVisibleC.value = true;
  formData.name = row.name;
  formData.number = row.number;
  formData.password = row.password;
  formData.isVIP = row.is_vip;
  formData.isAdmin = row.is_admin;
  formData.status = row.status;
  formDataCopy.name = row.name;
  formDataCopy.number = row.number;
  formDataCopy.password = row.password;
  formDataCopy.isVIP = row.is_vip;
  formDataCopy.isAdmin = row.is_admin;
  formDataCopy.status = row.status;
};

const onConfirmChange = () => {
  // 真实业务请发起请求
  editUser();
  confirmVisibleD.value = false;
  confirmVisibleC.value = false;
};

const editUser = async () => {
  try {
    const response = await axios.post('/api/admin/editUsers', formData);
    console.log(response);
    if (response.data.success) {
      MessagePlugin.success('修改成功');
    } else {
      MessagePlugin.error('修改发生错误');
    }
  } catch (e) {
    console.log(e);
  } finally {
    fetchData();
  }
};

onMounted(() => {
  fetchData();
});

const headerAffixedTop = computed(
  () =>
    ({
      offsetTop: store.isUseTabsRouter ? 48 : 0,
      container: `.${prefix}-layout`,
    }) as any, // TO BE FIXED
);
</script>

<style lang="less" scoped>
.list-common-table {
  background-color: var(--td-bg-color-container);
  padding: var(--td-comp-paddingTB-xxl) var(--td-comp-paddingLR-xxl);
  border-radius: var(--td-radius-medium);

  .table-container {
    margin-top: var(--td-comp-margin-xxl);
  }
}

.form-item-content {
  width: 100%;
}

.operation-container {
  display: flex;
  justify-content: flex-end;
  align-items: center;

  .expand {
    .t-button__text {
      display: flex;
      align-items: center;
    }
  }
}

.payment-col {
  display: flex;

  .trend-container {
    display: flex;
    align-items: center;
    margin-left: var(--td-comp-margin-s);
  }
}
</style>
